package com.cloud.lan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.lan.api.dto.req.WxDataReq;
import com.cloud.lan.api.dto.resp.LanUserResp;
import com.cloud.lan.dao.LanUserMapper;
import com.cloud.lan.dao.LanUserWxMapper;
import com.cloud.lan.entity.base.BaseResponse;
import com.cloud.lan.entity.base.exceptions.BaseException;
import com.cloud.lan.entity.constant.WxDataConstant;
import com.cloud.lan.entity.enums.RedisKeyEnum;
import com.cloud.lan.entity.model.dataobject.LanUserDO;
import com.cloud.lan.entity.model.dataobject.LanUserWxDO;
import com.cloud.lan.service.ILanUserService;
import com.cloud.lan.service.tx.wx.WxInitService;

import org.springframework.stereotype.Service;

import java.util.Map;

import javax.annotation.Resource;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author xyqierkang@163.com
 * @since 2021-12-06
 */
@Slf4j
@Service
public class LanUserServiceImpl extends ServiceImpl<LanUserMapper, LanUserDO> implements ILanUserService {

    @Resource
    LanUserMapper lanUserMapper;
    @Resource
    LanUserWxMapper lanUserWxMapper;
    @Resource
    WxInitService wxInitService;

    @Resource
    RedisService redisService;

    String wxDataUrl = "https://api.weixin.qq.com/datacube/{}?access_token={}";

    @Override
    public LanUserResp getUserInfo(String token) {
        LambdaQueryWrapper<LanUserWxDO> wxQw = new LambdaQueryWrapper<>();
        wxQw.eq(LanUserWxDO::getToken, token);
        LanUserWxDO lanUserWxDO = lanUserWxMapper.selectOne(wxQw);
        LanUserResp lanUserResp = new LanUserResp();
        if (lanUserWxDO == null) {
            log.error("getUserInfo查询用户空 {}", token);
            return lanUserResp;
        }
        LambdaQueryWrapper<LanUserDO> qw = new LambdaQueryWrapper<>();
        qw.eq(LanUserDO::getOpenId, lanUserWxDO.getOpenId());
        LanUserDO lanUserDO = lanUserMapper.selectOne(qw);
        BeanUtil.copyProperties(lanUserDO, lanUserResp);
        lanUserResp.setUserPhone(DesensitizedUtil.mobilePhone(lanUserResp.getUserPhone()));
        lanUserResp.setUserName(StrUtil.isNotEmpty(lanUserDO.getUserName()) ? lanUserDO.getUserName() : lanUserDO.getWxName());
        lanUserResp.setUserHead(StrUtil.isNotEmpty(lanUserDO.getUserHead()) ? lanUserDO.getUserHead() : lanUserDO.getWxHead());
        return lanUserResp;
    }

    @Override
    public BaseResponse<Object> getWxData(WxDataReq req) {
        // 先获取当前时间-1天
        Long st = Long.parseLong(DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -1).toJdkDate(), "yyyyMMdd"));
        // 获取前端传入的时间
        Long et = Long.parseLong(req.getBegin_date());
        log.info("获取 {} 开始时间 {} 结束时间：{}", req.getMethod(), st, et);
        if (st > et) {
            log.info("开始大于结束 进行微信数据实时查询 {}", req.getMethod());
            // 说明当前时间大于传入的时间 进行微信实时统计查询
            String accessToken = wxInitService.getAccessToken();
            try {
                String url = StrUtil.format(wxDataUrl, WxDataConstant.getMethod.apply(req.getMethod()), accessToken);
                Map<String, Object> map = Convert.convert(new TypeReference<Map<String, Object>>() {}, req);
                String mapParams = JSONUtil.toJsonStr(map);
                log.info("获取 getWxData 请求WX的url：{} body 组装的数据：{}", url, mapParams);
                String result = HttpUtil.post(url, mapParams);
                log.info("获取 getWxData result：{}", result);
                return BaseResponse.success(result);
            } catch (Exception e) {
                log.error("获取 getAccessToken 失败", e);
                throw new BaseException(BaseResponse.ERROR, e.getMessage());
            }
        }
        return BaseResponse.success(redisService.getCommonRedis(RedisKeyEnum.WX_DATA_METHOD.key(req.getMethod())));
    }
}
